package com.tt.mymu.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tt.mymu.entity.UserView;
import com.tt.mymu.mapper.UserViewMapper;
import com.tt.mymu.service.UserViewService;
import com.tt.mymu.utils.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

@Service
public class UserViewServiceImpl implements UserViewService {
    @Autowired
    private UserViewMapper userViewMapper;
    private static final Logger logger = LoggerFactory.getLogger(UserViewServiceImpl.class);

    public void insertUserViewByUser(UserView userView) {
        userViewMapper.insert(userView);
    }

    @Override
    public Result updateUserViewEndTimeById(int id, String endTime) {

        int update = userViewMapper.updateUserViewEndTimeById(id, endTime);
        return Result.success(update);
    }

    /**
     * 每天早上5点查询过期会员并将状态修改为0
     */
    public void getUserViewListUpdateOverTime() {
        QueryWrapper<UserView> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);
        List<UserView> userViews = userViewMapper.selectList(queryWrapper);
        for (UserView userView : userViews) {
            if (!eqTimeEndBoolean(userView.getEndTime())) {
                userView.setStatus(0);
                userView.setUpdateTime(new Date());
                userViewMapper.updateById(userView);
            }
        }
    }

    /**
     * 根据用户id获取视频信息 ,返回视频是否可看
     *
     * @param userId
     * @return
     */
    @Override
    public Result getUserViewByUserId(int userId) {
        QueryWrapper<UserView> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        UserView userView = userViewMapper.selectOne(queryWrapper);
        if (null == userView) {
            return Result.build(1, "时间已经过期");
        }
        if (null == userView.getEndTime()) {
            return Result.build(1, "时间已经过期");
        }
        // 解析字符串时间,返回为true：数据库时间比现在时间大
        boolean b = eqTimeEndBoolean(userView.getEndTime());
        if (b) {
            return Result.success();
        }
        return Result.build(1, "时间已经过期");
    }


    /**
     * 更新用户时间，如果用户时间过期根据 status 状态添加时间
     * 如果时间未过去但是用户想增加时间，当前时间 + 添加的时间
     *
     * @param id
     * @param status
     * @return
     */
    @Override
    public Result updateUserViewEndTime(int id, int status) {
        logger.info("用户id {id}", id, "，状态{status}", status);
        // 后去用户数据库时间
        UserView userViewEnd = userViewMapper.selectById(id);
        Date endTime = userViewEnd.getEndTime();
        if (endTime == null) {
            endTime = new Date();
        }
        boolean b = eqTimeEndBoolean(endTime);
        if (!b) {
            endTime = new Date();
        }
        Date date = addTimeEnd2Data(endTime, status);
        QueryWrapper<UserView> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);

        UserView userView = new UserView();
        userView.setEndTime(date);
        //userView.setStatus(1);
        int update = userViewMapper.update(userView, queryWrapper);
        if (update != 1) {
            return Result.build(1, "时间更新失败");
        }
        return Result.success(update);
    }


    /**
     * 时间的添加 根据status添加当前月
     *
     * @param endTime
     * @param status
     * @return
     */
    private Date addTimeEnd2Data(Date endTime, int status) {

        // 转换为LocalDateTime
        LocalDateTime dateTime = LocalDateTime.ofInstant(endTime.toInstant(), java.time.ZoneId.systemDefault());
        // 增加一个月还是几个月根据status来添加
        LocalDateTime nextMonth = dateTime.plusMonths(status);

        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 转换并输出
        String formattedDateTime = nextMonth.format(formatter);
        return new Date(formattedDateTime);
    }

    /**
     * 比较2个时间 数据库时间和现在时间比较如果 >返回 true,< false
     *
     * @param endTime
     * @return
     */
    private boolean eqTimeEndBoolean(Date endTime) {
        // 转换为LocalDateTime
        LocalDateTime dateTime = LocalDateTime.ofInstant(endTime.toInstant(), java.time.ZoneId.systemDefault());
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        LocalDateTime parsedTime = LocalDateTime.parse(endTime, formatter);
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 比较时间
        if (now.isBefore(dateTime)) {
            return true;
        }
        return false;

    }

}
